package com.realtyManage.springboot.Interceptor;

import com.realtyManage.springboot.GlobalException.TokenException;
import com.realtyManage.springboot.Model.Security;
import com.realtyManage.springboot.Utils.SpringContextUtil;
import io.jsonwebtoken.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * JWTAuthenticationFilter
 * token的校验
 * 该类继承自BasicAuthenticationFilter，在doFilterInternal方法中，
 * 从http头的Authorization 项读取token数据，然后用Jwts包提供的方法校验token的合法性。
 * 如果校验通过，就认为这是一个取得授权的合法请求
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/6/30
 **/
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);

        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        Security securityCfg = (Security) SpringContextUtil.getBean("security");
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new TokenException("Token为空");
        }
        String user = null;
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(securityCfg.getKey())
                    .parseClaimsJws(token.replace("Bearer ", ""))
                    .getBody();
            user = claims.getSubject();
            if (user != null) {
                //验证level
                ArrayList<Map<String,String>> arr = (ArrayList<Map<String,String>>) claims.get("level");
                String level = arr.get(0).get("authority");

                HttpSession session = request.getSession();
                if (session.isNew()) {
                    session.setAttribute("level", level);
                    session.setAttribute("user", user);
                }else{
                    //session.invalidate();
                }
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
        } catch (ExpiredJwtException e) {
            logger.error("Token已过期: {} " + e);
            throw new TokenException("Token已过期");
        } catch (UnsupportedJwtException e) {
            logger.error("Token格式错误: {} " + e);
            throw new TokenException("Token格式错误");
        } catch (MalformedJwtException e) {
            logger.error("Token没有被正确构造: {} " + e);
            throw new TokenException("Token没有被正确构造");
        } catch (SignatureException e) {
            logger.error("签名失败: {} " + e);
            throw new TokenException("签名失败");
        } catch (IllegalArgumentException e) {
            logger.error("非法参数异常: {} " + e);
            throw new TokenException("非法参数异常");
        }
        return null;
    }

}
